package com.rupeng.service;

import com.rupeng.annotation.RupengCacheable;
import com.rupeng.annotation.RupengClearCache;
import com.rupeng.annotation.RupengUseCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rupeng.pojo.AdminUser;
import com.rupeng.util.CommonUtils;
import com.rupeng.util.ImageCodeUtils;

@Service
@RupengCacheable
public class AdminUserService extends BaseService<AdminUser> {
	@Autowired
	private AdminUserRoleService adminUserRoleService;
	@RupengUseCache
	public AdminUser login(String account, String password) {
		AdminUser adminUser = new AdminUser();
		adminUser.setAccount(account);
		adminUser = super.selectOne(adminUser);
		if (adminUser!=null) {
			if (adminUser.getPassword().equalsIgnoreCase(CommonUtils.calculateMD5(adminUser.getPasswordSalt()+password))) {
				return adminUser;
			}
		}
		return null;
	}
	@RupengClearCache
	public void insert(AdminUser adminUser, Long[] roleIds) {
		String passwordSalt = ImageCodeUtils.generateCode(6);
		adminUser.setPasswordSalt(passwordSalt);
		adminUser.setPassword(CommonUtils.calculateMD5(passwordSalt+adminUser.getPassword()));
		super.insert(adminUser);
		AdminUser pojo = new AdminUser();
		pojo.setAccount(adminUser.getAccount());
		adminUser = super.selectOne(pojo);
		adminUserRoleService.updateFirst(adminUser.getId(), roleIds);
	}
	@RupengClearCache
	public void resetPassword(Long id, String password) {
		AdminUser adminUser = super.selectOne(id);
		String passwordSalt = adminUser.getPasswordSalt();
		adminUser.setPassword(CommonUtils.calculateMD5(passwordSalt+password));
		super.update(adminUser);
	}
	
}